﻿
using AutoMapper;
using IdGen;
using Newtonsoft.Json;
using Ross.EntityFramework;
using Ross.EntityFramework.Model;
using Ross.Service.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ross.Service
{
    public class TargetService : BaseService, IDisposable
    {
        private TranDbContext dbContext;
        public IRepository<Targets, int> repository;
        public IRepository<Users, int> userresp;
        

        public TargetService(string nameOrConnectionString)
        {
            dbContext = new TranDbContext(nameOrConnectionString);
            repository = new Repository<Targets, int>(dbContext);
            userresp = new Repository<Users, int>(dbContext);
            
        }

        public ResultDto<bool> NewInsert(Dto.NewZongBiao input)
        {
            var result = new ResultDto<bool>();
            try
            {
                var model = Mapper.Map<Targets>(input);
                model.StartingTime = Convert.ToDateTime(input.Timespan[0]);
                model.PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]);
                var pdepth = repository.Get(input.ParentTargetID).Depth;
                model.Depth = pdepth + 1;
                repository.Insert(model);
                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }

            return result;
        }

        public ResultDto<List<Dto.TargetOutput>> NewChaXunZongBiao2(string keywords = "", string departId = "", string status = "", string timespan = "")
        {
            //按年份查询根节点，0，1，N
            //子节点为空时，child=null
            //部门为空时，默认查询所有授权部门
            //部门的深度为3
            //var result = new ResultDto<List<Dto.NewZongBiao>>();
            List<Dto.TargetOutput> trees = new List<TargetOutput>();
            List<Dto.TargetOutput> zhanlue = new List<TargetOutput>();
            ResultDto<List<Dto.TargetOutput>> result = new ResultDto<List<Dto.TargetOutput>>();
            var listsAll = repository.GetAllList();
            if (!string.IsNullOrEmpty(username))
            {
                var user = userresp.GetAllList(o => o.UserName == username || o.EmpID == username).FirstOrDefault();
                string[] adepts = user.AuthorizedDepartment.Split(',');
                Expression<Func<Targets, bool>> expression = o => o.Depth == 3 && o.TargetName == year.ToString();
                if (!string.IsNullOrEmpty(keywords))
                    expression = expression.ExpressionAnd(t => t.TargetName.Contains(keywords));
                if (!string.IsNullOrEmpty(departId))
                    expression = expression.ExpressionAnd(t => t.Department == departId);
                else
                    expression = expression.ExpressionAnd(t => adepts.Contains(t.Department));
                if (!string.IsNullOrEmpty(status))
                    expression = expression.ExpressionAnd(t => t.ApprovalStatus == status);
                if (!string.IsNullOrEmpty(timespan))
                {
                    DateTime starttime = Convert.ToDateTime(timespan.Split(',')[0]);
                    DateTime endtime = Convert.ToDateTime(timespan.Split(',')[1]);
                    expression = expression.ExpressionAnd(t => t.StartingTime >= starttime && t.StartingTime <= endtime);
                }
                var lists = repository.GetAllList(expression).ToList();
                foreach (var item in lists)
                {
                    TargetOutput obj = new TargetOutput();
                    obj = Mapper.Map<Dto.TargetOutput>(item);
                    obj.children = GetTargetsTree(listsAll, item.ID);
                    if (obj.children.Count == 0)
                        obj.children = null;
                    trees.Add(obj);
                }
            }
            result.total = trees.Count;
            result.datas = trees;

            var n = repository.GetAllList();


            return result;

        }
        public ResultDto<List<Dto.TargetOutput>> NewChaXunBuMen()
        {

            var result = new ResultDto<List<Dto.TargetOutput>>();
            Expression<Func<Targets, bool>> expression = o => o.Depth <= 3;
            var lists = repository.GetAllList(expression);
            var trees = GetTargetsTree(lists, -1);
            //var model = Mapper.Map<NewZongBiao>(trees);

            var tree = trees.Where(u => u.TargetName == year.ToString()).ToList();

            if (tree.Count == 1)
            {
                result.status = 200;
                result.datas = tree.First().children;
                return result;
            }
            else if (tree.Count == 0)
            {
                result.message = $"无{year}年度记录";
                result.status = 500;
                result.datas = null;
                return result;
            }

            throw new Exception($"根节点错误，存在多个{year}年度节点");


        }

        public ResultDto<bool> NewUpdate(Dto.NewZongBiao input)
        {

            ResultDto<bool> result = new ResultDto<bool>();
            try
            {

                var bumen = repository.Get(input.ID);

                //if (bumen.ApprovalStatus != "未审核")
                //{
                //    result.message = $"{bumen.ApprovalStatus}状态下不允许修改";
                //    result.status = 500;
                //    result.datas = false;
                //    return result;
                //}

                bumen.Department = input.Department;
                bumen.TargetName = input.TargetName;
                bumen.TargetDescription = input.TargetDescription;
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.AssessmentMethod = input.AssessmentMethod;
                bumen.AccountingMethod = input.AccountingMethod;
                bumen.Statistician = input.Statistician;
                bumen.ResourceSupport = input.ResourceSupport;
                bumen.Budget1 = input.Budget1;
                bumen.Budget2 = input.Budget2;
                bumen.Budget3 = input.Budget3;
                bumen.CostCategory1 = input.CostCategory1;
                bumen.CostCategory2 = input.CostCategory2;
                bumen.CostCategory3 = input.CostCategory3;
                bumen.Responsible = input.Responsible;


                bumen.ApprovalStatus = input.ApprovalStatus;
                //bumen.Version = input.Version;
                bumen.ReviseTime = DateTime.Now;

                bumen.StartingTime = Convert.ToDateTime(input.Timespan[0]);
                bumen.PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]);

                repository.Update(bumen);


                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        } //end

        public ResultDto<bool> NewApproveTarget(int id, string status)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            var t = repository.Get(id);

            if (status == "审核中")
            {
                t.ApprovalStatus = status;
                t.ApprovalTime = DateTime.Now;
                repository.Update(t);
                result.status = 200;
                result.datas = true;
                return result;
            }
            if (status == "未审核")
            {
                //未审核更新此节点
                //然后更新所有子节点
                var lists = repository.GetAllList();
                t.ApprovalStatus = status;
                t.ApprovalTime = DateTime.Now;


                var zijiedians = GetTargetsTree(lists, id);

                if (!ChangeApproveTarget(zijiedians))
                {
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                repository.Update(t);
                result.status = 200;
                result.datas = true;
                return result;
                
            }

            //当节点深度为3时，


            t.ApprovalStatus = status;
            t.ApprovalTime = DateTime.Now;
            repository.Update(t);
            result.status = 200;
            result.datas = true;
            return result;

            ////提交审核中时，上级必须为已审核

            //var p = repository.Get(t.ParentTargetID).ApprovalStatus;
            //if (p == "已审核")
            //{
            //    t.ApprovalStatus = status;
            //    t.ApprovalTime = DateTime.Now;
            //    repository.Update(t);
            //    result.status = 200;
            //    result.datas = true;
            //    return result;
            //}

            //result.message = "上层目标未审核通过";
            //result.status = 500;
            //result.datas = false;
            //return result;
        }

        public ResultDto<bool> NewDelete(int id)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var obj = repository.Get(id);

                //if (obj.ApprovalStatus != "未审核")
                //{
                //    result.message = $"{obj.ApprovalStatus}状态下不允许删除";
                //    result.status = 500;
                //    result.datas = false;
                //    return result;
                //}

                if (repository.GetAllList(o => o.ParentTargetID == id).Count != 0)
                {
                    result.message = $"子目标存在的情况下不允许删除";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }
                repository.Delete(id);

                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        }

        public  ResultDto<bool> InsertGen(Dto.TargetsOutput input)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            //前端创建，提供ID:-1时，生成跟节点；不提供时，生成子节点
                var targetsgongsi = new Targets()
                {
                    ParentTargetID = -1,
                    Classification = input.Classification,
                    TargetName = input.TargetName,
                    Department = input.Department,
                    ApprovalStatus = "已审核",
                    Version = input.Version,
                    CreationTime = DateTime.Now,
                    Lock = false,
                    Approver = "001",
                    StartingTime=Convert.ToDateTime(input.Timespan[0]),
                    PlannedCompletionTime= Convert.ToDateTime(input.Timespan[1]),
                    TargetDescription=input .TargetDescription,
                    Depth=0,
                };
                var id = repository.InsertAndGetId(targetsgongsi);
                input.ParentTargetID = id;

            Targets targetbumen = new Targets()
            {
                ParentTargetID = input.ParentTargetID,
                Classification = input.Classification,
                TargetName = input.DepTargetName,
                AssessmentCriteria = input.AssessmentCriteria,
                Department = input.Department,
                ApprovalStatus = "未审核",
                Version = input.Version,
                CreationTime = DateTime.Now,
                Lock = false,
                Approver = "001",
                StartingTime = Convert.ToDateTime(input.Timespan[0]),
                PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]),
                TargetDescription = input.TargetDescription,
                Depth=1,
            };
            repository.Insert(targetbumen);
            result.status = 200;
            result.datas = true;
            return result;
        }

        public ResultDto<bool> InsertZi(Dto.TargetsOutput input)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            
            Targets targetbumen = new Targets()
            {
                ParentTargetID = input.ParentTargetID,
                Classification = input.Classification,
                TargetName = input.DepTargetName,
                AssessmentCriteria = input.AssessmentCriteria,
                Department = input.Department,
                ApprovalStatus = "未审核",
                Version = input.Version,
                CreationTime = DateTime.Now,
                Lock = false,
                Approver = "001",
                StartingTime = Convert.ToDateTime(input.Timespan[0]),
                PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]),
                TargetDescription = input.TargetDescription,
                Depth=1,
            };
            repository.Insert(targetbumen);
            result.status = 200;
            result.datas = true;
            return result;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public ResultDto<List<Dto.TargetOutput>> GetAllList(string keywords = "", string departId = "", string status = "",string version = "")
        {
            ResultDto<List<Dto.TargetOutput>> result = new ResultDto<List<Dto.TargetOutput>>();
            Expression<Func<Targets, bool>> expression = o => o.ID > 0;
            if (!string.IsNullOrEmpty(keywords))
                expression = expression.ExpressionAnd(t => t.TargetName.Contains(keywords));
            if (!string.IsNullOrEmpty(departId))
                expression = expression.ExpressionAnd(t => t.Department == departId);
            if (!string.IsNullOrEmpty(status))
                expression = expression.ExpressionAnd(t => t.ApprovalStatus == status);
            if (!string.IsNullOrEmpty(version))
                expression = expression.ExpressionAnd(t => t.Version == version);

            if (!string.IsNullOrEmpty(username))
            {
                var obj = userresp.GetAllList(o => o.UserName == username).FirstOrDefault();
                if (obj != null)
                {
                    expression = expression.ExpressionAnd(t => obj.AuthorizedDepartment.Contains(t.Department));
                }
            }
            var lists = repository.GetAllList(expression);
            result.datas = Mapper.Map<List<Dto.TargetOutput>>(lists);
            result.total = lists.Count;
            return result;
        }

        public ResultDto<bool> NewXiuBian(BuMenBiaoOutput input)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            //已审核状态下才可修编
            if (input.ApprovalStatus != "已审核")
            {
                result.message = $"已审核状态下才可修编";
                result.status = 500;
                result.datas = false;
                return result;
            }

            //点修编提交整颗年度树
            //移除未审核

            var all = repository.GetAllList().ToList();

            var historyrepositorys = new Repository<History, int>(dbContext);
            foreach (var t in all)
            {
                History history = new History()
                {
                    SourceID = t.ID,
                    Classification = t.Classification,
                    Department = t.Department,
                    TargetName = t.TargetName,
                    TargetDescription = t.TargetDescription,
                    AssessmentCriteria = t.AssessmentCriteria,
                    AssessmentMethod = t.AssessmentMethod,
                    AccountingMethod = t.AccountingMethod,
                    Statistician = t.Statistician,
                    ResourceSupport = t.ResourceSupport,
                    Responsible = t.Responsible,
                    PlanningDocumentURL = t.PlanningDocumentURL,
                    Lock = t.Lock,
                    TargetState = t.TargetState,
                    ParentTargetID = t.ParentTargetID,
                    CreationTime = t.CreationTime,
                    StartingTime = t.StartingTime,
                    PlannedCompletionTime = t.PlannedCompletionTime,
                    ActualCompletionTime = t.ActualCompletionTime,
                    ReviseTime = t.ReviseTime,
                    Approver = t.Approver,
                    ApprovalStatus = t.ApprovalStatus,
                    ApprovalTime = t.ApprovalTime,
                    Version = input.Version,//拿表单的
                    Depth = t.Depth,
                    Budget1 = t.Budget1,
                    Budget2 = t.Budget2,
                    Budget3 = t.Budget3,
                    CostCategory1 = t.CostCategory1,
                    CostCategory2 = t.CostCategory2,
                    CostCategory3 = t.CostCategory3,
                };
                historyrepositorys.Insert(history);
            }


            //再更新当前表
            try
            {
                var bumen = repository.Get(input.ID);

                bumen.Classification = input.Classification;
                bumen.Department = input.Department;
                bumen.TargetName = input.TargetName;
                bumen.TargetDescription = input.TargetDescription;
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.AssessmentMethod = input.AssessmentMethod;
                bumen.AccountingMethod = input.AccountingMethod;
                bumen.Statistician = input.Statistician;
                bumen.ResourceSupport = input.ResourceSupport;
                bumen.Budget1 = input.Budget1;
                bumen.Budget2 = input.Budget2;
                bumen.Budget3 = input.Budget3;
                bumen.CostCategory1 = input.CostCategory1;
                bumen.CostCategory2 = input.CostCategory2;
                bumen.CostCategory3 = input.CostCategory3;
                bumen.Responsible = input.Responsible;
                bumen.ApprovalStatus = "未审核";
                bumen.Version = input.Version;
                bumen.ReviseTime = DateTime.Now;

                bumen.StartingTime = input.StartingTime;
                bumen.PlannedCompletionTime = input.PlannedCompletionTime;

                repository.Update(bumen);


                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }

            //同时子节点刷新未审核
            var lists = repository.GetAllList();

            var zijiedians = GetTargetsTree(lists, input.ID);
            //刷新子节点
            if (!ChangeApproveTarget(zijiedians))
            {
                result.status = 500;
                result.datas = false;
                return result;
            }

            //如果当前深度为战略目标，修编结束后，修改发布状态为false

            var end = repository.Get(input.ID);
            if (end.Depth == 2)
            {
                var d3 = repository.GetAllList(o => o.Depth == 3).Where(u => u.ParentTargetID == input.ID).ToList();


                //子集修改
                foreach (var i in d3)
                {
                    i.Lock = false;
                    repository.Update(i);
                }
            }

            return result;

        }

        public ResultDto<List<Dto.TargetOutput>> GetTreeList(string keywords = "", string departId = "", string status = "", string version = "")
        {
            ResultDto<List<Dto.TargetOutput>> result = new ResultDto<List<Dto.TargetOutput>>();
            var lists = repository.GetAllList();
            var resp = GetTargetsTree(lists);
            result.total = resp.Count;
            result.datas = resp;
            return result;
        }

        private List<Dto.TargetOutput> GetTargetsTree(List<Targets> datas, int parentid = -1)
        {
            List<Dto.TargetOutput> result = new List<Dto.TargetOutput>();
            var lists = datas.Where(o => o.ParentTargetID == parentid).ToList();
            foreach(var item in lists)
            {
                Dto.TargetOutput obj = new Dto.TargetOutput();
                obj = Mapper.Map<Dto.TargetOutput>(item);
                var childrens = datas.Where(o => o.ParentTargetID == item.ID).ToList();
                if(childrens.Count>0)
                {
                    obj.children = GetTargetsTree(datas, item.ID);
                }
                result.Add(obj);
            }
            return result;
        }

        private List<Dto.TargetInput> GetTargets(List<Dto.TargetOutput> datas)
        {
            List<Dto.TargetInput> result = new List<Dto.TargetInput>();
            foreach (var item in datas)
            {
                Dto.TargetInput obj = new Dto.TargetInput();
                obj = Mapper.Map<Dto.TargetInput>(item);
                if (item.children!=null)
                {
                    GetTargets(item.children);
                }
                result.Add(obj);
            }
            return result;
        }

        public ResultDto<List<Dto.TargetsOutput>> ChaXunZongBiao()
        {
            var result = new ResultDto<List<Dto.TargetsOutput>>();
            //查公司级的未审核，审核中
            Expression<Func<Targets, bool>> expGongSiJi = t => t.ParentTargetID == -1 ;
            //查询公司级未审核的
            var gongSiJi = repository.GetAllList(expGongSiJi);
            var zongbiao = repository.GetAllList();
            var childrens = new List<Dto.TargetsOutput>();
            //其对应下级
            foreach (var i in gongSiJi)
            {
                var buMenJi = zongbiao.Where(t => t.ParentTargetID == i.ID).ToList();

                //其子节点集合
                foreach (var j in buMenJi)
                {
                    var childeren = new Dto.TargetsOutput()
                    {
                        ID = j.ID,
                        Department = j.Department,
                        TargetName = i.TargetName,
                        DepTargetName=j.TargetName,
                        Classification = j.Classification,
                        AssessmentCriteria = j.AssessmentCriteria,
                        ParentTargetID = j.ParentTargetID,
                        ApprovalStatus = j.ApprovalStatus,
                    };
                    childrens.Add(childeren);
                }
            }
            result.datas = childrens;
            return result;
        } //end

        public ResultDto<bool> Delete(int id)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var obj = repository.Get(id);

                if(obj.ApprovalStatus!="未审核")
                {
                    result.message = $"{obj.ApprovalStatus}状态下不允许删除";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                //查询其父节点
                //查询父节点所有子节点一次
                //遍历所有子节点ID
                //删除所有ID
             
                var fujiedian = repository.Get(obj.ParentTargetID);
                var zijiedians = repository.GetAllList(t => t.ParentTargetID == fujiedian.ID);
                var ids=zijiedians.Select(o => o.ID).ToList();

                //任何一个子节点的子节点存在，也不能删除
                var x= repository.GetAllList().Where(o => id==o.ParentTargetID).ToList();

                if (x.Count!=0)
                {
                    result.message = $"子目标存在的情况下不允许删除";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }
                if(ids.Count==1)
                {
                    repository.Delete(id);
                    repository.Delete(fujiedian.ID);
                }

                repository.Delete(id);
                TongBuShanChu(id);
                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        }

        public ResultDto<bool> Deletebumen(int id)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var obj = repository.Get(id);

                if (obj.Depth < 2)
                {
                    result.message = "无权删除此节点";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                if (obj.ApprovalStatus != "未审核")
                {
                    result.message = $"{obj.ApprovalStatus}状态下不允许删除";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                if(repository.GetAllList(o=>o.ParentTargetID==id).Count!=0)
                {
                    result.message = $"子目标存在的情况下不允许删除";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }
                //查询所有子节点父节点为此节点
                //添加此节点
                //删除所有ID
                var zijiedians = repository.GetAllList(t => t.ParentTargetID == id);
                var ids = zijiedians.Select(o => o.ID).ToList();
                ids.Add(id);

                foreach (var i in ids)
                {
                    repository.Delete(i);
                    TongBuShanChu(i);
                }

                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public ResultDto<bool> ApproveTarget(int id,string status)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            var t = repository.Get(id);

            if(status=="审核中")
            {
                t.ApprovalStatus = status;
                t.ApprovalTime = DateTime.Now;
                repository.Update(t);
                result.status = 200;
                result.datas = true;
                return result;
            }
            if(status =="未审核")
            {
                //未审核更新此节点
                //然后更新所有子节点
                var lists = repository.GetAllList();
                t.ApprovalStatus = status;
                t.ApprovalTime = DateTime.Now;


                var zijiedians= GetTargetsTree(lists,id);
                 
                if(!ChangeApproveTarget(zijiedians))
                {
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                repository.Update(t);
                result.status = 200;
                result.datas = true;
                return result;
                //
            }

            //提交审核中时，上级必须为已审核

            var p = repository.Get(t.ParentTargetID).ApprovalStatus;
            if(p=="已审核")
            {
                t.ApprovalStatus = status;
                t.ApprovalTime = DateTime.Now;
                repository.Update(t);
                result.status = 200;
                result.datas = true;
                return result;
            }

            result.message = "上层目标未审核通过";
            result.status = 500;
            result.datas = false;
            return result;
        }

        /// <summary>
        /// 发布
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public ResultDto<bool> FaBu(int id, bool status)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            var t = repository.Get(id);
            var p = repository.Get(t.ParentTargetID);
            p.ApprovalStatus = "已审核";
            repository.Update(p);

            t.Lock = status;
            repository.Update(t);
            result.status = 200;
            result.datas = true;
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="outputs"></param>
        /// <returns></returns>
        public bool ChangeApproveTarget(List<TargetOutput> outputs)
        {
            try
            {
                foreach (var i in outputs)
                {
                    //修改每个节点
                     var t= repository.Get(i.ID);
                    t.ApprovalStatus = "未审核";
                    repository.Update(t);
                    if (i.children != null)
                    {
                        ChangeApproveTarget(i.children);
                    }
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
        public ResultDto<bool> Update(Dto.TargetsOutput input)
        {

            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var gognsi = repository.Get(input.ParentTargetID);
                var bumen = repository.Get(input.ID);
                

                if (bumen.ApprovalStatus!="未审核")
                {
                    result.message = $"{bumen.ApprovalStatus}无法修改";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                gognsi.ID = input.ParentTargetID;
                gognsi.Classification = input.Classification;
                gognsi.TargetName = input.TargetName;
                gognsi.ApprovalStatus = input.ApprovalStatus;
                gognsi.Version = input.Version;
                gognsi.ReviseTime = DateTime.Now;
                gognsi.TargetDescription = input.TargetDescription;
                gognsi.StartingTime = Convert.ToDateTime(input.Timespan[0]);
                gognsi.PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]);


                bumen.Classification = input.Classification;
                bumen.TargetName = input.DepTargetName;
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.Department = input.Department;
                bumen.ApprovalStatus = input.ApprovalStatus;
                bumen.Version = input.Version;
                bumen.ReviseTime = DateTime.Now;
                bumen.TargetDescription = input.TargetDescription;
                bumen.StartingTime = Convert.ToDateTime(input.Timespan[0]);
                bumen.PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]);
        
                repository.Update(bumen);
                repository.Update(gognsi);

                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        } //end

        public ResultDto<Targets> GetTarget(int id)
        {
            ResultDto<Targets> result = new ResultDto<Targets>();
            Expression<Func<Targets, bool>> expression = o => o.ID == id;
            var t = repository.GetAllList(expression);
            if (t.Count == 0)
            {
                result.message = "无效ID";
                result.status = 500;
                result.datas = null;
                return result;
            }
            result.status = 200;
            result.datas = t.First();
            return result;
        }

        /// <summary>
        /// 表锁定条件
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        public bool LockTable(string exp)
        {
            if (exp == "审核中" || exp == "已审核")
                return true;
            return false;
        }

        public ResultDto<string> GetDepartment()
        {
            ResultDto<string> result = new ResultDto<string>();
            List<string> dep = new List<string>();
            string obj = "";

            //根据id 查询授权部门
            if (string.IsNullOrEmpty(username))
            {
                result.message = "用户名不能为空";
                result.status = 500;
                return result;
            }
            obj = userresp.GetAllList(o => o.UserName == username).FirstOrDefault().AuthorizedDepartment;

            result.status = 200;
            result.datas = obj;
            return result;
        }

        public List<Depart> GetDeptAsync()
        {
            ResultDto<List<Service.Dto.Depart>> result = new ResultDto<List<Service.Dto.Depart>>();
            //后续联系杨凯雨拿到管理员账号才可以拉取全部门名称
            string url = BudgetServer + "/api/Department/GetAllList?userId=000022";
            var t = Task.Run(async () =>
            {
                string response = await RemoteGet(url);
                result = JsonConvert.DeserializeObject<ResultDto<List<Service.Dto.Depart>>>(response);
            });
            t.Wait();
            return result.datas;
        }

        public async Task<List<Service.Dto.ExpenseCate>> GetCateAsync()
        {
            ResultDto<List<Service.Dto.ExpenseCate>> result = new ResultDto<List<Service.Dto.ExpenseCate>>();
            string url = BudgetServer + "/api/Expense/GetAllList";
            string response = await RemoteGet(url);
            result = JsonConvert.DeserializeObject<ResultDto<List<Service.Dto.ExpenseCate>>>(response);
            var t = result.datas;
            return t;
        }

        /// <summary>
        /// 部门表插入
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ResultDto<bool> Insert(Dto.BuMenBiaoOutput input)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            var pDepth = repository.Get(input.ParentTargetID).Depth;

            if(pDepth>2)
            {
                //深度为3不可再添加
                result.message = "不可再添加子目标";
                result.status = 500;
                result.datas = false;
                return result;
            }

            Targets targetbumen = new Targets()
            {
                ParentTargetID = input.ParentTargetID,
                Classification = input.Classification,
                Department = input.Department,
                TargetName = input.TargetName,
                TargetDescription = input.TargetDescription,
                AssessmentCriteria = input.AssessmentCriteria,
                AssessmentMethod = input.AssessmentMethod,
                AccountingMethod = input.AccountingMethod,
                Statistician = input.Statistician,
                Responsible = input.Responsible,
                ApprovalStatus = "未审核",
                Version = input.Version,
                CreationTime = DateTime.Now,
                Lock = false,
                StartingTime = Convert.ToDateTime(input.Timespan[0]),
                PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]),
                Budget1 = input.Budget1,
                Budget2 = input.Budget2,
                Budget3 = input.Budget3,
                CostCategory1 = input.CostCategory1,
                CostCategory2 = input.CostCategory2,
                CostCategory3 = input.CostCategory3,
                ResourceSupport = input.ResourceSupport,
                Depth = pDepth + 1,
            };
            repository.Insert(targetbumen);
            result.status = 200;
            result.datas = true;
            return result;
        }

        /// <summary>
        /// 部门表更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ResultDto<bool> Update(Dto.NewZongBiao input)
        {

            ResultDto<bool> result = new ResultDto<bool>();
            try
            {

                var bumen = repository.Get(input.ID);

                if (bumen.ApprovalStatus != "未审核")
                {
                    result.message = $"{bumen.ApprovalStatus}状态下不允许修改";
                    result.status = 500;
                    result.datas = false;
                    return result;
                }

                bumen.Department = input.Department;
                bumen.TargetName = input.TargetName;
                bumen.TargetDescription = input.TargetDescription;
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.AssessmentMethod = input.AssessmentMethod;
                bumen.AccountingMethod = input.AccountingMethod;
                bumen.Statistician = input.Statistician;
                bumen.ResourceSupport = input.ResourceSupport;
                bumen.Budget1 = input.Budget1;
                bumen.Budget2 = input.Budget2;
                bumen.Budget3 = input.Budget3;
                bumen.CostCategory1 = input.CostCategory1;
                bumen.CostCategory2 = input.CostCategory2;
                bumen.CostCategory3 = input.CostCategory3;
                bumen.Responsible = input.Responsible;

                
                bumen.ApprovalStatus = input.ApprovalStatus;
                //bumen.Version = input.Version;
                bumen.ReviseTime = DateTime.Now;
                
                bumen.StartingTime = Convert.ToDateTime(input.Timespan[0]);
                bumen.PlannedCompletionTime = Convert.ToDateTime(input.Timespan[1]);

                repository.Update(bumen);
         

                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        } //end

        public ResultDto<List<Targets>> GetResourceTarget()
        {
            ResultDto<List<Targets>> result = new ResultDto<List<Targets>>();
            var shouquans = GetShouQuan().datas.Split(',');
            var resources = repository.GetAllList();
            var t = resources.Where(o => shouquans.Contains(o.ResourceSupport)).ToList();
            result.status = 200;
            result.datas = t;
            return result;
        }

        /// <summary>
        /// 根据内存中的用户名获取到用户的整体信息（此项不包含密码）
        /// </summary>
        /// <returns></returns>
        public ResultDto<Dto.oUser> Get()
        {
            ResultDto<Dto.oUser> result = new ResultDto<Dto.oUser>();
            var repositorys = new Repository<Users, int>(dbContext);
            try
            {
                if (oPrincipal != null)
                {
                    var obj = repositorys.GetAllList(o => o.UserName == username).FirstOrDefault();
                    if (obj != null)
                    {
                        result.status = 200;
                        result.datas = Mapper.Map<Dto.oUser>(obj);
                    }
                    else
                    {
                        result.message = "user is not exist";
                        result.status = 500;
                    }
                }
                else
                {
                    result.message = "Unable to access unauthorized app";
                    result.status = 500;
                }
            }
            catch (Exception e)
            {
                result.message = e.Message;
                result.status = 500;
            }
            return result;
        }

        /// <summary>
        /// 获得授权部门
        /// </summary>
        /// <returns></returns>
        public ResultDto<string> GetShouQuan()
        {
            ResultDto<string> result = new ResultDto<string>();
            var shouquans = Get().datas.AuthorizedDepartment;
            result.status = 200;
            result.datas = shouquans;
            return result;
        }

        public ResultDto<bool> GaiTargetState(int id, string status)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            var t = repository.Get(id);
            t.TargetState = status;
            if (status == "已完成")
                t.ActualCompletionTime = DateTime.Now;
            else
                t.ActualCompletionTime = Convert.ToDateTime(null);
            repository.Update(t);
            result.status = 200;
            result.datas = true;
            return result;
        }

        /// <summary>
        /// 部门
        /// </summary>
        /// <param name="buMenBiaoOutput"></param>
        /// <returns></returns>
        public ResultDto<bool> XiuBian(BuMenBiaoOutput input)
        {
            ResultDto<bool> result = new ResultDto<bool>();

            //已审核状态下才可修编
            if (input.ApprovalStatus != "已审核")
            {
                result.message = $"已审核状态下才可修编";
                result.status = 500;
                result.datas = false;
                return result;
            }

            //先插入历史表
            var all = repository.GetAllList().ToList();

            var historyrepositorys = new Repository<History, int>(dbContext);
            foreach (var t in all)
            {
                History history = new History()
                {
                    SourceID = t.ID,
                    Classification = t.Classification,
                    Department = t.Department,
                    TargetName = t.TargetName,
                    TargetDescription = t.TargetDescription,
                    AssessmentCriteria = t.AssessmentCriteria,
                    AssessmentMethod = t.AssessmentMethod,
                    AccountingMethod = t.AccountingMethod,
                    Statistician = t.Statistician,
                    ResourceSupport = t.ResourceSupport,
                    Responsible = t.Responsible,
                    PlanningDocumentURL = t.PlanningDocumentURL,
                    Lock = t.Lock,
                    TargetState = t.TargetState,
                    ParentTargetID = t.ParentTargetID,
                    CreationTime = t.CreationTime,
                    StartingTime = t.StartingTime,
                    PlannedCompletionTime = t.PlannedCompletionTime,
                    ActualCompletionTime = t.ActualCompletionTime,
                    ReviseTime = t.ReviseTime,
                    Approver = t.Approver,
                    ApprovalStatus = t.ApprovalStatus,
                    ApprovalTime = t.ApprovalTime,
                    Version = input.Version,//拿表单的
                    Depth = t.Depth,
                    Budget1 = t.Budget1,
                    Budget2 = t.Budget2,
                    Budget3 = t.Budget3,
                    CostCategory1 = t.CostCategory1,
                    CostCategory2 = t.CostCategory2,
                    CostCategory3 = t.CostCategory3,
                };
                historyrepositorys.Insert(history);
            }


            //再更新当前表
            try
            {
                var bumen = repository.Get(input.ID);

                bumen.Classification = input.Classification;
                bumen.Department = input.Department;
                bumen.TargetName = input.TargetName;
                bumen.TargetDescription = input.TargetDescription;
                bumen.AssessmentCriteria = input.AssessmentCriteria;
                bumen.AssessmentMethod = input.AssessmentMethod;
                bumen.AccountingMethod = input.AccountingMethod;
                bumen.Statistician = input.Statistician;
                bumen.ResourceSupport = input.ResourceSupport;
                bumen.Budget1 = input.Budget1;
                bumen.Budget2 = input.Budget2;
                bumen.Budget3 = input.Budget3;
                bumen.CostCategory1 = input.CostCategory1;
                bumen.CostCategory2 = input.CostCategory2;
                bumen.CostCategory3 = input.CostCategory3;
                bumen.Responsible = input.Responsible;
                bumen.ApprovalStatus = "未审核";
                bumen.Version = input.Version;
                bumen.ReviseTime = DateTime.Now;

                bumen.StartingTime = input.StartingTime;
                bumen.PlannedCompletionTime = input.PlannedCompletionTime;

                repository.Update(bumen);


                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }

            //同时子节点刷新未审核
            var lists = repository.GetAllList();

            var zijiedians = GetTargetsTree(lists, input.ID);
            //刷新子节点
            if (!ChangeApproveTarget(zijiedians))
            {
                result.status = 500;
                result.datas = false;
                return result;
            }


            var end = repository.Get(input.ID);
            if (end.Depth == 2)
            {
                var d3 = repository.GetAllList(o => o.Depth == 3).Where(u => u.ParentTargetID == input.ID).ToList();


                //子集修改
                foreach (var i in d3)
                {
                    i.Lock = false;
                    repository.Update(i);
                }
            }

            return result;
            
        }

        public ResultDto<List<History>> ShowVersion(int id)
        {
            var result = new ResultDto<List<History>>();
            var repositoryhistory = new Repository<History, int>(dbContext);
            //查询历史记录
            var t = repositoryhistory.GetAllList(o=>o.SourceID==id).OrderByDescending(o=>o.ID).ToList();
            
            result.datas = t;
            result.status = 200;
            return result;
        }

        /// <summary>
        ///同步删除历史版本
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool TongBuShanChu(int id)
        {
            var repository = new Repository<History, int>(dbContext);
            var delids = repository.GetAllList(o => o.SourceID == id);

            try
            {
                foreach (var i in delids)
                {
                    repository.Delete(i);
                }
            }
            catch
            {
                return false;
            }

            return true;
        }


         //向下查
        private List<NewZongBiao>  NewGetTargetsTree(List<NewZongBiao> datas,List<NewZongBiao> nodes)
        {
            //遍历每个集合
            foreach(var i in nodes)
            {
                //他的子节点
                var lists = datas.Where(u => u.ParentTargetID == i.ID).ToList();

                //加入子节点
                i.children = lists;
                NewGetTargetsTree(datas, i.children);
            }
            return nodes;
        }

        public ResultDto<List <NewZongBiao>> NewTree()
        {
            var nodes =repository.GetAllList(i=>i.ID==1);

            var result = new ResultDto<List<NewZongBiao>>();

            var t = NewGetTargetsTree(Mapper.Map<List<NewZongBiao>>(repository.GetAllList()), Mapper.Map<List<NewZongBiao>>(nodes));
            result.datas = t;
            return result;
        }
      

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            dbContext.Dispose();
        }

    }
}
